package com.vipshop.core.base.impl;

import com.vipshop.core.base.BaseRepository;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.List;
public class BaseRepositoryImpl<T, PrimaryKey extends Serializable> extends SimpleJpaRepository<T, PrimaryKey> implements BaseRepository<T, PrimaryKey> {

    private final EntityManager entityManager; //父类没有不带参数的构造方法，这里手动构造父类

    public BaseRepositoryImpl(JpaEntityInformation<T, PrimaryKey> entityInformation,
                       EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityManager = entityManager;
    }

    /**
     * 使用原生sql 查询 list列表
     * @param sql
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<Object[]> listBySQL(String sql) {
        return entityManager.createNativeQuery(sql).getResultList();
    }

    /**
     * 使用原生sql 查询 list列表
     * @param sql
     * @param clzss
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<T> findListByNativeSql(String sql, Class<T> clzss) {
        return entityManager.createNativeQuery(sql, clzss).getResultList();
    }
}
